<?php
/***************************************************************************
 * @Description:
 * 
 * @FileName:         FieldController.php
 * @Author :          liyong5@staff.sina.com.cn
 * @CreatedTime:      Mon 28 May 2018 06:17:50 PM CST
 ************************************************************************/

namespace app\modules\core\controllers;

use Yii;
use yii\data\Pagination;
use yii\data\ActiveDataProvider;
use app\modules\core\models\Field;
use app\modules\core\models\Validator;

class FieldController extends DefaultController
{
    public function actions() {
        return array_merge(parent::actions(), []);
    }

    public function actionList() {
        $query = Field::find()->where([]);
        $pagination = new Pagination([
            'defaultPageSize' => 20,
            'totalCount' => $query->count(),
        ]);

        $fields = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();

        return $this->render('list', ['fields' => $fields, 'pagination' => $pagination]);
    }

    public function actionInstall() {
        $request = Yii::$app->request;
        $field = new Field();

        if (null === $request->post('classNs')) {
            return $this->render('install', ['field' => $field]);
        }

        if (! $field->load($request->post())) {
            return $this->render('install', ['field' => $field]);
        }

        if ($field->validate() && $field->createField()) {
            return $this->redirect(['/core/field/list']);
        }

        return $this->render('install', ['field' => $field]);
    }

    public function actionCreate() {
        $request = Yii::$app->request;
        $field = new Field();

        $validators = Validator::find()
            ->where(['enable' => '1'])
            ->all();

        
        $list = [];
        foreach ($validators as $validate) {
            $list[$validate['id']] = $validate['name'];
        }

        if (null === $request->post('id')) {
            return $this->render('create', ['field' => $field, 'validators' => $list]); 
        }
        if (! $field->load($request->post())) {
            return $this->render('create', ['field' => $field, 'validators' => $list]); 
        }

        $field->author = '';
        $field->ctime = time();
        if ($field->validate() && $field->save()) {
            return $this->redirect(['/core/field/list']);
        }

        return $this->render('create', ['field' => $field, 'validators' => $list]); 
    }

    public function actionAll() {
        $fields = Field::find()
            ->where([])
            ->all();

        return $this->asJson($fields);
    }
}
